/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-10-13
 * Time: 23:16
 */
public class test_2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * <p>
     * 判断岛屿数量
     *
     * @param grid char字符型二维数组
     * @return int整型
     */
    int[] dx = {0, 0, 1, -1};
    int[] dy = {-1, 1, 0, 0};
    int[][] vim;
     int m, n;

    public int solve(char[][] grid) {
         m = grid.length;
         n = grid[0].length;
        vim = new int[m][n];
        int sum = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(grid, i, j)) {
                    sum++;
                }
            }
        }
        return sum;
    }

    private boolean dfs(char[][] grid, int i, int j) {
        if (grid[i][j] == '0' || vim[i][j] == 1) {
            return false;
        }
        vim[i][j] = 1;
        int k;
        for (k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && vim[x][y] == 0) {
                dfs(grid, x, y);
            }
        }
        return true;
    }
}
